<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-17
 * Time: 15:03
 * 故障报修
 *
 * 集合malfunction
 * 故障信息  (storeId, position,  deviceNum,  people,    datetime,  content, imgs,   peopleIds,       state,  receiverPeople, deviceName)
 *            门店Id   故障位置    设备编号    报修人id   报修时间   内容      图片[]  可以领取人的id[]  未完成    领取人ID       设备名称
 * 			  string   string	  string	  string     string     string    array    array          string    string         string
 *
 */

namespace app\index\controller;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style;
class Malfunction
{
    const malfunction = [
        'storeId'=>'',       //门店Id  storemanage
        'position'=>'',      //故障位置
        'deviceNum'=>'',     //设备编号
        'deviceName'=>'',    //设备名称
        'people'=>'',        //报修人id
        'peopleName'=>'',    //保修人名字
        'datetime'=>'',      //报修时间
        'content'=>'',       //内容
        'imgs'=>[],          //图片[]
        'peopleIds'=>NULL,   //可以领取人的id[]
        'state'=>'未领取',   //未完成
        'receiverPeople'=>'',//领取人ID
        'receiverName'  =>'',//领取人名字
        'maintainContent'=>'', //维修内容
        'maintainImgs'   =>[], //维修图片
        'maintainDatetime'=>'',//结束报修时间
    ];
    public static function getData($where, $one = true, $table = 'malfunction')
    {
        return ($one == true) ? getFirst(mongo($table)->where($where)->select()) : mongo($table)->where($where)->select();
    }
    public static function setData($where, $data, $table = 'malfunction')
    {
        mongo($table)->where($where)->update($data);
    }
    public static function insertData($data, $table = 'malfunction')
    {
        mongo($table)->insert($data);
        return mongo($table)->getLastInsID();
    }
    public static function deleteData($where, $table = 'malfunction')
    {
        mongo($table)->where($where)->delete();
    }
    /**
     * 派单
     * @param string $id          //超时 的id
     * @param null $position     //故障位置
     * @param null $deviceNum    //设备号
     * @param null $deviceName   //设备名字
     * @param null $datetime     //报修时间
     * @param null $content      //报修内容
     * @param array $imgs[]      //图片  base64
     * @return array
     */
    public static function sendOrdersDb($position = '', $deviceNum = '', $deviceName = '', $content= '', $imgs=[], $peopleIds = [], $id = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id          = input('id');
        $position    = input('position');
        $deviceName  = input('deviceName');
        $deviceNum   = input('deviceNum');
        $content     = input('content');
        $imgs        = input('imgs/a', []);
        $peopleIds   = input('peopleIds/a', []);

        $userName = User::getData(['id'=>cookie('userId')])['username'] ?? '';
        $insertData = [
            'storeId'     => User::getStoreId(),
            'position'    => $position,
            'deviceNum'   => $deviceNum,
            'deviceName'  => $deviceName,
            'people'      => cookie('userId'),
            'peopleName'  => $userName,
            'datetime'    => date('Y-m-d H:i'),
            'content'     => $content,
            'imgs'        => $imgs,
        ];
        if(!empty($id) && !empty($peopleIds)) {
            $insertData['peopleIds'] = $peopleIds;  //经理派单
            self::setData(['id'=>$id], ['state'=>'已重新派单']);
        }
        if(empty($id) && !empty($peopleIds)) {
            $insertData['peopleIds'] = $peopleIds;  //经理派单
        }
        $lastId = self::insertData(array_merge(self::malfunction, $insertData));
        return RD(SUCCESS, self::getData(['id'=>$lastId]));
    }

    /**
     * 获取所有故障单
     * @param string $dateTime  报修时间
     * @param string $keyword   报修人
     * @param string $state     状态   未领取  已领取  已完成  超时
     * @param string $currentPage当前页
     * @param string $pageSize  页面大小
     * @return array
     */
    public static function getAllOrdersDb($dateTime = '', $keyword = '', $state = '', $currentPage = '', $pageSize = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $dateTime   = input('dateTime');
        $keyword    = input('keyword');
        $state      = input('state');
        $currentPage= input('currentPage');
        $pageSize   = input('pageSize');

        //检查是否有超时的
        $date=date_create();
        date_sub($date,date_interval_create_from_date_string("1 minute"));
        $overTime =  date_format($date,"Y-m-d H:i");

        $where = [
            'storeId'    => User::getStoreId(),
            'datetime'   => ['<', $overTime],
            'peopleIds'  => 'NULL',
            'state'      => '未领取',
        ];

        $result = self::getData($where, false);
        foreach ($result as $key=>$value) {
            self::setData(['id'=>$value['id']], ['state'=>'超时']);  //超时
        }
        //获取所有故障单
        $where = [
            'storeId'    => User::getStoreId(),
            'datetime'   => ['like', $dateTime.'.*'],
            'peopleName' => ['like', $keyword.'.*'],
            'state'      => ['like', $state.'.*'],
        ];

        $position = (User::getData(['id'=>cookie('userId')])['rankName'] ?? '');

        if($position == '经理') {
            $result = self::getData($where, false);
            //排序
            $my_sort = function ($a, $b) {
                switch ($a['state']) {
                    case '未领取':
                        $avalue = 5;
                        break;
                    case '已领取':
                        $avalue = 4;
                        break;
                    case '超时':
                        $avalue = 6;
                        break;
                    case '已完成':
                        $avalue = 3;
                        break;
                    case '已重新派单':
                        $avalue = 2;
                        break;
                }
                switch ($b['state']) {
                    case '未领取':
                        $bvalue = 5;
                        break;
                    case '已领取':
                        $bvalue = 4;
                        break;
                    case '超时':
                        $bvalue = 6;
                        break;
                    case '已完成':
                        $bvalue = 3;
                        break;
                    case '已重新派单':
                        $bvalue = 2;
                        break;
                }
                if ($avalue == $bvalue)
                    return 0;
                return ($avalue < $bvalue)? 1: -1;
            };
            usort($result, $my_sort);  //排序
        } else {
            $where['peopleIds']  = 'NULL';
            $result = self::getData($where, false);

            $where['peopleIds']  = cookie('userId');
            $result1 = self::getData($where, false);

            $result = array_append($result, $result1);  //追加数据
            //排序
            $my_sort = function ($a, $b) {
                switch ($a['state']) {
                    case '未领取':
                        $avalue = 6;
                        break;
                    case '已领取':
                        $avalue = 5;
                        break;
                    case '超时':
                        $avalue = 4;
                        break;
                    case '已完成':
                        $avalue = 3;
                        break;
                    case '已重新派单':
                        $avalue = 2;
                        break;
                }
                switch ($b['state']) {
                    case '未领取':
                        $bvalue = 6;
                        break;
                    case '已领取':
                        $bvalue = 5;
                        break;
                    case '超时':
                        $bvalue = 4;
                        break;
                    case '已完成':
                        $bvalue = 3;
                        break;
                    case '已重新派单':
                        $bvalue = 2;
                        break;
                }
                if ($avalue == $bvalue)
                    return 0;
                return ($avalue < $bvalue)? 1: -1;
            };
            usort($result, $my_sort);  //排序
        }
        $count = count($result);
        $finished = 0;
        foreach ($result as $value)
        {
            if($value['state'] == '已完成') {
                $finished++;
            }
        }
        array_paging($result, ($currentPage - 1)* $pageSize, $pageSize);

        return RD(SUCCESS, ['total'=>$count, 'finished'=>$finished, 'currentPage'=>$currentPage, 'orders'=>$result]);
    }
    /**
     * 编辑故障单
     * @param string $id
     * @param string $position
     * @param string $deviceNum
     * @param string $content
     * @param string $deviceName
     * @param array  $imgs
     * @return array
     */
    public static function editAllOrdersDb($id = '', $position = '', $deviceNum = '', $content = '', $deviceName = '', $imgs=[])
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id          = input('id');
        $position    = input('position');
        $deviceName  = input('deviceName');
        $deviceNum   = input('deviceNum');
        $content     = input('content');
        $imgs        = input('imgs/a', []);
        if(empty($id))
            return RD(PARA_NOT_NULL);

        $updateData = [
            'position'    => $position,
            'deviceNum'   => $deviceNum,
            'deviceName'  => $deviceName,
            'content'     => $content,
            'imgs'        => $imgs,
        ];

        self::setData(['id'=>$id], $updateData);
        return RD(SUCCESS, $updateData);
    }
    /**
     * 领取故障单
     * @param null $id         故障单id
     * @param null $reciverName领取人ID
     * @return array
     */
    public static function getOrdersDb($id = null, $reciverName = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id     = input('id');
        $reciverName = input('reciverName');
        $receiverName = User::getData(['id'=>$reciverName])['username'] ?? '';

        if(empty($id))
            return RD(PARA_NOT_NULL);

        self::setData(['id'=>$id], ['receiverPeople' => $reciverName,  'receiverName'=>$receiverName, 'state' => '已领取']);
        $data = self::getData(['id'=>$id], false);
        return RD(SUCCESS, $data);
    }

    /** 结束报修
     * @param string $id                  故障单id
     * @param string $maintainContent     维修内容
     * @param array $maintainImgs         维修图片
     * @return array
     */
    public static function finishMaintainDb($id = '', $maintainContent = '', $maintainImgs = [])
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id = input('id');
        if(empty($id))
            return RD(PARA_NOT_NULL);
        $maintainContent = input('maintainContent');
        $maintainImgs    = input('maintainImgs/a');

        self::setData(['id'=>$id], ['state' => '已完成', 'maintainContent'=>$maintainContent, 'maintainImgs'=>$maintainImgs, 'maintainDatetime'=>date('Y-m-d H:i')]);
        return RD(SUCCESS);
    }

    /**多文件导出
     * @param array $ids
     * @return array
     */
    public static function multiexportReportMalfunction($ids = [])
    {
        if(!empty($perssion = perssion([LOGIN, SHOP]))) { return RD(NO_LOGIN);}  //权限判断
        $ids = input('ids/a', []);
        if(empty($ids))
            return RD(PARA_NOT_NULL);
        $ids = json_decode($ids[0] ?? '');
        $filenames = [];
        foreach ($ids as $id) {
            $filename = self::exportReportMalfunction($id);
            array_push($filenames, $filename);
        }

        $zipName = '作业单批量下载.zip';
        $zip = new \ZipArchive;//使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
        if ($zip->open($zipName, \ZIPARCHIVE::OVERWRITE | \ZIPARCHIVE::CREATE)!==TRUE) {
            return RD(FAIL, '无法打开文件，或者文件创建失败');
        }
        foreach ($filenames as $filename) {
            if(file_exists($filename)){
                $zip->addFile($filename, $filename);//第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
            }
        }
        $zip->close();
        foreach ($filenames as $filename) {
            @unlink($filename);
        }
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=".$zipName);
        readfile($zipName);
        @unlink($zipName);
    }

    /**导出故障报修单
     * @param string $id
     */
    public static function oneexportReportMalfunction($id = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))
            return $perssion;
        $id = input('id');
        if(empty($id))
            return RD(PARA_NOT_NULL);

        $filename = self::exportReportMalfunction($id);
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=".$filename);
        readfile($filename);
        @unlink($filename);
    }

    /** 导出一个故障单
     * @param string $id 故障单id
     * @return 文件路径
     */
    public static function exportReportMalfunction($id)
    {
        $result = self::getData(['id'=>$id]);
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();

        $worksheet->setTitle('故障报修');

        $worksheet->getColumnDimension('A')->setWidth(20);
        $worksheet->getColumnDimension('B')->setWidth(20);
        $worksheet->getColumnDimension('C')->setWidth(20);
        $worksheet->getColumnDimension('D')->setWidth(20);

        $currentIndex = 1;
        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->getStyleByColumnAndRow(1, $currentIndex)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER_CONTINUOUS);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '故障报修');
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '故障设备:'.($result['deviceName'] ?? ''));
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '报修位置:'.($result['position'] ?? ''));
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '设备编号:'.($result['deviceNum'] ?? ''));
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '报修人:'.($result['peopleName'] ?? ''));
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '报修时间:'.($result['datetime'] ?? ''));
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '报修内容:'.($result['content'] ?? ''));
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '报修图片:');
        $currentIndex++;

        $images = [];
        foreach ($result['imgs'] as $key=>$value) {
            $filename = base64_image_content($value, 'outImagetemp');

            $drawing = new Drawing();
            $drawing->setName('报修图片');
            $drawing->setDescription('PhpSpreadsheet logo');
            $drawing->setPath($filename);
            $drawing->setHeight(80);
            $drawing->setOffsetX($key * 50);
            $drawing->setCoordinates('A'.$currentIndex);
            $drawing->setWorksheet($worksheet);
            array_push($images, $filename);
            $currentIndex++;
        }

        $currentIndex += 4;
        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->getStyleByColumnAndRow(1, $currentIndex)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER_CONTINUOUS);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '维修');
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '维修内容:'.($result['maintainContent'] ?? ''));
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '维修时间:'.($result['maintainDatetime'] ?? ''));
        $currentIndex++;

        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '维修图片:');
        $currentIndex++;

        $maintainimages = [];
        $result['maintainImgs'] = empty($result['maintainImgs']) ? [] : $result['maintainImgs'];
        foreach (($result['maintainImgs'] ?? []) as $key=>$value) {
            $filename = base64_image_content($value, 'outImagetemp');

            $drawing = new Drawing();
            $drawing->setName('报修图片');
            $drawing->setDescription('PhpSpreadsheet logo');
            $drawing->setPath($filename);
            $drawing->setHeight(40);
            $drawing->setOffsetX($key * 50);
            $drawing->setCoordinates('A'.$currentIndex);
            $drawing->setWorksheet($worksheet);
            array_push($maintainimages, $filename);
            $currentIndex++;
        }
        $writer = new Xls($spreadsheet);
        $filename = '故障报修'.$result['deviceNum'].'--'.uuid().'.xls';
        $writer->save($filename);
        //删除文件
        foreach ($images as $image) {
            @unlink($image);
        }
        foreach ($maintainimages as $image) {
            @unlink($image);
        }
        return $filename;
    }
}